package cn.icebreak.cartoon.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description：通用适配器
 * Created by xiaoqiang1369 on 2016/6/8.
 */
@SuppressLint("UseSparseArrays")
public abstract class CommonListAdapter<E> extends BaseAdapter {

	public List<E> list;

	public Context mContext;

	public LayoutInflater mInflater;

	public List<E> getList() {
		return list;
	}

	public void setList(List<E> list) {
		this.list = list;
		notifyDataSetChanged();
	}

	public void add(E e) {
		this.list.add(e);
		notifyDataSetChanged();
	}

	public void addAll(List<E> list) {
		this.list.addAll(list);
		notifyDataSetChanged();
	}

	public void remove(int position) {
		this.list.remove(position);
		notifyDataSetChanged();
	}

	public CommonListAdapter(Context context, List<E> list) {
		super();
		this.mContext = context;
		this.list = list;
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		convertView = bindView(position, convertView, parent);
		//添加控件的点击事件
		addInternalClickListener(convertView, position, list.get(position));


		return convertView;
	}

	public abstract View bindView(int position, View convertView, ViewGroup parent);

	// adapter item中注册了点击事件的控件与其响应事件的集合
	public Map<Integer, onInternalClickListener> canClickItem;

	private void addInternalClickListener(final View itemV, final Integer position, final Object valuesMap) {
		if (canClickItem != null) {
			for (Integer key : canClickItem.keySet()) {
				View inView = itemV.findViewById(key);
				final onInternalClickListener inviewListener = canClickItem.get(key);
				if (inView != null && inviewListener != null) {
					inView.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							inviewListener.OnClickListener(itemV, v, position, valuesMap);
						}
					});
				}
			}
		}
	}

	/**
	 * 添加 监听器
	 * @param key view 的 id
	 * @param onClickListener
     */
	public void setOnInViewClickListener(Integer key, onInternalClickListener onClickListener) {
		if (canClickItem == null) {
			canClickItem = new HashMap<Integer, onInternalClickListener>();
		}
		canClickItem.put(key, onClickListener);
	}

	public interface onInternalClickListener {
		public void OnClickListener(View parentV, View v, Integer position, Object values);
	}

	public Context getContext() {
		return mContext;
	}



//	abstract public @LayoutRes
//	int getLayoutRes();




}
